package edu.gmu.swe632.fruit.activity;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.net.ParseException;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jwetherell.compass.SensorsActivity;
import com.jwetherell.compass.data.GlobalData;

import edu.gmu.swe632.fruit.R;
import edu.gmu.swe632.fruit.service.GestureRecognizerService;
import edu.gmu.swe632.fruit.util.CustomAdapter;
import edu.gmu.swe632.fruit.util.RowData;
import event.GestureListener;
import event.StateEvent;

abstract public class DirectionActivity extends SensorsActivity implements GestureListener
{
	private static final String TAG = "directionactivity";
	private static final String[] title = new String[] { "Confirm" };
	private static final String[] detail = new String[] { "" };
	private static final Integer[] imgid = { R.drawable.check };

	private static WakeLock wakeLock = null;
	private static TextView text = null;
	private static View compassView = null;

	private LayoutInflater mInflater;
	private Vector<RowData> data;
	private RowData rd;
	private boolean isRecognizing = false;
	private boolean isAllowed = true;
	private Timer allowTimer = null;

	protected String direction = "0 N";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.direction);

		text = (TextView) findViewById(R.id.text);
		compassView = findViewById(R.id.compass);

		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");

		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		data = new Vector<RowData>();

		for (int i = 0; i < title.length; i++)
		{
			try
			{
				rd = new RowData(i, title[i], detail[i]);
			}
			catch (ParseException e)
			{
				e.printStackTrace();
			}
			data.add(rd);
		}

		CustomAdapter adapter = new CustomAdapter(this, mInflater, R.layout.list_item, R.id.title,
				data, imgid);
		setListAdapter(adapter);
		getListView().setTextFilterEnabled(true);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onDestroy()
	{
		super.onDestroy();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onStart()
	{
		super.onStart();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onStop()
	{
		super.onStop();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onResume()
	{
		super.onResume();

		wakeLock.acquire();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onPause()
	{
		super.onPause();

		wakeLock.release();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.sos_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_sos:
				startActivity(new Intent(this, SosActivity.class));
				break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_VOLUME_UP)
		{
			if (isAllowed)
			{
				if (isRecognizing)
				{
					Toast.makeText(this, GestureRecognizerService.CAPTURED, Toast.LENGTH_SHORT)
							.show();
					GestureRecognizerService.stopRecognizer();
				}
				else
				{
					Toast.makeText(this, GestureRecognizerService.CAPTURE, Toast.LENGTH_SHORT)
							.show();
					GestureRecognizerService.startRecognizer();
				}

				isRecognizing = !isRecognizing;
				isAllowed = false;
				Log.d(TAG, "disallow");
			}

			if (allowTimer != null)
				allowTimer.cancel();

			allowTimer = new Timer();
			allowTimer.schedule(new AllowTask(), 400);

			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	private class AllowTask extends TimerTask
	{
		@Override
		public void run()
		{
			DirectionActivity.this.isAllowed = true;
			Log.d(TAG, "allow");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onSensorChanged(SensorEvent evt)
	{
		super.onSensorChanged(evt);

		if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER
				|| evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
		{
			// Tell the compass to update it's graphics
			if (compassView != null)
				compassView.postInvalidate();
		}

		// Update the direction text
		direction = updateText(GlobalData.getBearing());
	}

	@Override
	public void stateReceived(StateEvent event)
	{
	}

	private static String updateText(float bearing)
	{
		int range = (int) (bearing / (360f / 16f));
		String dirTxt = "";
		if (range == 15 || range == 0)
			dirTxt = "N";
		else if (range == 1 || range == 2)
			dirTxt = "NE";
		else if (range == 3 || range == 4)
			dirTxt = "E";
		else if (range == 5 || range == 6)
			dirTxt = "SE";
		else if (range == 7 || range == 8)
			dirTxt = "S";
		else if (range == 9 || range == 10)
			dirTxt = "SW";
		else if (range == 11 || range == 12)
			dirTxt = "W";
		else if (range == 13 || range == 14)
			dirTxt = "NW";

		String dirStr = ((int) bearing) + " " + dirTxt;
		text.setText("Which direction?\n" + dirStr);

		return dirStr;
	}
}
